export default class Upload{
  constructor(object) {
    this.obj = {
      url: '',
      count: 6,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'],  // 可以指定来源是相册还是相机，默认二者都有
    }
    if(Object.prototype.toString.call(object) === "[object Object]"){
		
		Object.assign(this.obj, object);
    }else{
      wx.showToast({
        title: '参数必须为对象',
        icon:"icon",
        duration: 2000
      });
    }
     
 
    return this;
  }
  // 上传图片 返回一个图片的数组集合
  async uploadPic(){
    let chooseImageResult = await this.chooseImage()
    // console.log("选择图片",chooseImageResult)
	
	
	
	// return;
    let imgArr = await chooseImageResult.tempFilePaths.map(async (item,index) => {
      wx.showLoading({
        title: `正在上传第${index+1}张`
      });
      let uploadFileResult = await this.uploadFile(item)
      // console.log("上传图片返回结果",uploadFileResult)
		
      return uploadFileResult.data;
    })
 
    return new Promise((resolve,reject) => {
      Promise.all(imgArr).then((result)=>{
        wx.hideLoading();
        wx.showToast({
          title: '上传成功',
          icon:"none",
          duration: 2000
        });
        // console.log("上传图片结果",result)
        resolve(result)
      })
    }) 
  }
  uploadFile(file){
    return new Promise((resolve, reject) => {
      wx.uploadFile({
       url: this.obj.url,
       filePath: file,
       name: 'file',
       success: function (res) {
        var data = res.data;
		var datas = JSON.parse(data);
		// console.log(datas);
		if(datas.code==0) {
			wx.showToast({
				title: datas.msg,
				icon:"none",
				duration: 3000 
			});return;
		}
        resolve(datas)
       },
       fail: function (res) {
        reject("上传失败")
       },
       complete: function (res) {
        wx.hideToast();
        wx.hideLoading();
       }
      })
    })
  }
  chooseImage(){
	  let that = this;
    return new Promise((resolve,reject) => {
      wx.chooseImage({
        count: this.obj.count,
        sizeType: this.obj.sizeType,
        sourceType: this.obj.sourceType,
        success: function (res) {
			
			if(2524005  <  res.tempFiles[0].size) {
				wx.showToast({
				  title: '图片大小不得超过2.5M',
				  icon:"none",
				  duration: 2000
				});
				return;
			}else {
					resolve(res)
			}
			
		},
        fail:function(){
          reject("选择文件失败")
        }
      })
    })
  }
	photoCompress(file, objDiv) {
		var ready = new FileReader();
		ready.readAsDataURL(file);
		const _this = this;
		ready.onload = function() {
			var fileResult = this.result;
			_this.canvasDataURL(fileResult, objDiv)
		}
	}
	canvasDataURL(path, callback) {
			var img = new Image();
	                 img.src = path;
	                var objCompressed = {}
	                 img.onload = function() {
	                     var that = this;
	                     //默认压缩后图片规格
	                   var quality = 0.7;
	                    var w = that.width;
	                    var h = that.height;
	                    var scale = w / h;
						//实际要求
	                    w = objCompressed.width || w;
	                    h = objCompressed.height || (w / scale);
	                    //生成canvas
	                   var canvas = document.createElement('canvas');
	                   var ctx = canvas.getContext('2d');
	                   // 创建属性节点
	                  var anw = document.createAttribute("width");
	                   anw.nodeValue = w;
	               var anh = document.createAttribute("height");
	                   anh.nodeValue = h;
	               canvas.setAttributeNode(anw);
	                   canvas.setAttributeNode(anh);
	                    ctx.drawImage(that, 0, 0, w, h);
	
	                  var base64 = canvas.toDataURL('image/jpeg', quality);
	                    // 回调函数返回base64的值
	                  callback(base64);
	                }
	           }
	 dataURLtoFile(dataurl,filename) {
	                 var arr = dataurl.split(","),
	                     mime = arr[0].match(/:(.*?);/)[1],
	                     bstr = atob(arr[1]),
	                    n = bstr.length,
	                    u8arr = new Uint8Array(n);
	                 while (n--) {
	                     u8arr[n] = bstr.charCodeAt(n);
	              }
	                return new File([u8arr],filename,  { type: mime });
	           }		   
}